<template>
  <div class="student-management">
    <div class="header">
      <h2>学生管理</h2>
      <div class="actions">
        <button class="btn btn-outline" @click="showImportModal = true">
          <i class="fas fa-upload"></i>
          批量导入
        </button>
        <button class="btn btn-outline" @click="exportStudents">
          <i class="fas fa-download"></i>
          导出列表
        </button>
        <button class="btn btn-primary" @click="showCreateModal = true">
          <i class="fas fa-plus"></i>
          添加学生
        </button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filters">
      <div class="search-box">
        <i class="fas fa-search"></i>
        <input 
          v-model="searchQuery" 
          type="text" 
          placeholder="搜索学生姓名、学号或邮箱"
          @input="handleSearch"
        >
      </div>
      <select v-model="statusFilter" @change="loadStudents">
        <option value="">全部状态</option>
        <option value="active">启用</option>
        <option value="inactive">禁用</option>
      </select>
      <select v-model="gradeFilter" @change="loadStudents">
        <option value="">全部年级</option>
        <option value="2021">2021级</option>
        <option value="2022">2022级</option>
        <option value="2023">2023级</option>
        <option value="2024">2024级</option>
      </select>
    </div>

    <!-- 学生列表 -->
    <div class="table-container">
      <table class="students-table">
        <thead>
          <tr>
            <th>
              <input 
                type="checkbox" 
                :checked="isAllSelected" 
                @change="toggleSelectAll"
              >
            </th>
            <th>学号</th>
            <th>姓名</th>
            <th>邮箱</th>
            <th>电话</th>
            <th>年级</th>
            <th>专业</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="student in students" :key="student.id">
            <td>
              <input 
                type="checkbox" 
                :value="student.id" 
                v-model="selectedStudents"
              >
            </td>
            <td>{{ student.student_id }}</td>
            <td>{{ student.name }}</td>
            <td>{{ student.email }}</td>
            <td>{{ student.phone || '-' }}</td>
            <td>{{ student.grade }}</td>
            <td>{{ student.major || '-' }}</td>
            <td>
              <span :class="['status', student.status]">
                {{ student.status === 'active' ? '启用' : '禁用' }}
              </span>
            </td>
            <td>{{ formatDate(student.created_at) }}</td>
            <td>
              <div class="actions">
                <button 
                  class="btn btn-sm btn-outline" 
                  @click="editStudent(student)"
                >
                  编辑
                </button>
                <button 
                  class="btn btn-sm btn-outline" 
                  @click="managePermissions(student)"
                >
                  权限
                </button>
                <button 
                  class="btn btn-sm btn-outline" 
                  @click="resetPassword(student)"
                >
                  重置密码
                </button>
                <button 
                  :class="['btn', 'btn-sm', student.status === 'active' ? 'btn-warning' : 'btn-success']"
                  @click="toggleStatus(student)"
                >
                  {{ student.status === 'active' ? '禁用' : '启用' }}
                </button>
                <button 
                  class="btn btn-sm btn-danger" 
                  @click="deleteStudent(student)"
                >
                  删除
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button 
        :disabled="currentPage === 1" 
        @click="changePage(currentPage - 1)"
      >
        上一页
      </button>
      <span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
      <button 
        :disabled="currentPage === totalPages" 
        @click="changePage(currentPage + 1)"
      >
        下一页
      </button>
    </div>

    <!-- 批量操作 -->
    <div v-if="selectedStudents.length > 0" class="batch-actions">
      <span>已选择 {{ selectedStudents.length }} 个学生</span>
      <button class="btn btn-danger" @click="batchDelete">
        批量删除
      </button>
    </div>

    <!-- 创建/编辑学生模态框 -->
    <div v-if="showCreateModal || showEditModal" class="modal-overlay" @click="closeModals">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>{{ showCreateModal ? '添加学生' : '编辑学生' }}</h3>
          <button class="close-btn" @click="closeModals">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveStudent">
            <div class="form-row">
              <div class="form-group">
                <label>学号 *</label>
                <input 
                  v-model="studentForm.student_id" 
                  type="text" 
                  required
                  :disabled="showEditModal"
                >
              </div>
              <div class="form-group">
                <label>姓名 *</label>
                <input v-model="studentForm.name" type="text" required>
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>邮箱 *</label>
                <input v-model="studentForm.email" type="email" required>
              </div>
              <div class="form-group">
                <label>电话</label>
                <input v-model="studentForm.phone" type="tel">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>年级 *</label>
                <select v-model="studentForm.grade" required>
                  <option value="">请选择年级</option>
                  <option value="2021">2021级</option>
                  <option value="2022">2022级</option>
                  <option value="2023">2023级</option>
                  <option value="2024">2024级</option>
                </select>
              </div>
              <div class="form-group">
                <label>专业</label>
                <input v-model="studentForm.major" type="text">
              </div>
            </div>
            <div v-if="showCreateModal" class="form-group">
              <label>密码 *</label>
              <input v-model="studentForm.password" type="password" required>
            </div>
            <div class="form-actions">
              <button type="button" class="btn btn-outline" @click="closeModals">
                取消
              </button>
              <button type="submit" class="btn btn-primary">
                {{ showCreateModal ? '创建' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 批量导入模态框 -->
    <div v-if="showImportModal" class="modal-overlay" @click="closeModals">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>批量导入学生</h3>
          <button class="close-btn" @click="closeModals">&times;</button>
        </div>
        <div class="modal-body">
          <div class="import-section">
            <div class="upload-area" @click="$refs.fileInput.click()">
              <i class="fas fa-cloud-upload-alt"></i>
              <p>点击选择Excel文件或拖拽文件到此处</p>
              <p class="file-info">支持 .xlsx, .xls 格式</p>
            </div>
            <input 
              ref="fileInput" 
              type="file" 
              accept=".xlsx,.xls" 
              @change="handleFileSelect" 
              style="display: none"
            >
            <div v-if="selectedFile" class="selected-file">
              <i class="fas fa-file-excel"></i>
              <span>{{ selectedFile.name }}</span>
              <button @click="selectedFile = null">&times;</button>
            </div>
          </div>
          <div class="template-section">
            <h4>导入模板</h4>
            <p>请按照以下格式准备Excel文件：</p>
            <table class="template-table">
              <thead>
                <tr>
                  <th>学号</th>
                  <th>姓名</th>
                  <th>邮箱</th>
                  <th>电话</th>
                  <th>年级</th>
                  <th>专业</th>
                  <th>密码</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>2024001</td>
                  <td>张三</td>
                  <td>zhangsan@example.com</td>
                  <td>13800138000</td>
                  <td>2024</td>
                  <td>计算机科学</td>
                  <td>123456</td>
                </tr>
              </tbody>
            </table>
            <button class="btn btn-outline btn-sm" @click="downloadTemplate">
              <i class="fas fa-download"></i>
              下载模板
            </button>
          </div>
          <div class="form-actions">
            <button type="button" class="btn btn-outline" @click="closeModals">
              取消
            </button>
            <button 
              type="button" 
              class="btn btn-primary" 
              :disabled="!selectedFile"
              @click="importFile"
            >
              开始导入
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 权限管理模态框 -->
    <div v-if="showPermissionModal" class="modal-overlay" @click="closeModals">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>权限管理 - {{ currentStudent?.name }}</h3>
          <button class="close-btn" @click="closeModals">&times;</button>
        </div>
        <div class="modal-body">
          <div class="permissions-list">
            <div v-for="permission in availablePermissions" :key="permission.key" class="permission-item">
              <label>
                <input 
                  type="checkbox" 
                  :value="permission.key" 
                  v-model="studentPermissions"
                >
                {{ permission.name }}
              </label>
              <p class="permission-desc">{{ permission.description }}</p>
            </div>
          </div>
          <div class="form-actions">
            <button type="button" class="btn btn-outline" @click="closeModals">
              取消
            </button>
            <button type="button" class="btn btn-primary" @click="savePermissions">
              保存权限
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { 
  getStudents, 
  createStudent, 
  updateStudent, 
  deleteStudent,
  batchDeleteStudents,
  resetStudentPassword,
  toggleStudentStatus,
  getStudentPermissions,
  updateStudentPermissions,
  importStudents,
  exportStudents as exportStudentsAPI
} from '@/api/rbac'

export default {
  name: 'StudentManagement',
  setup() {
    const students = ref([])
    const loading = ref(false)
    const searchQuery = ref('')
    const statusFilter = ref('')
    const gradeFilter = ref('')
    const selectedStudents = ref([])
    const currentPage = ref(1)
    const totalPages = ref(1)
    const pageSize = 10

    // 模态框状态
    const showCreateModal = ref(false)
    const showEditModal = ref(false)
    const showImportModal = ref(false)
    const showPermissionModal = ref(false)
    const currentStudent = ref(null)
    const selectedFile = ref(null)

    // 表单数据
    const studentForm = reactive({
      student_id: '',
      name: '',
      email: '',
      phone: '',
      grade: '',
      major: '',
      password: ''
    })

    // 权限相关
    const studentPermissions = ref([])
    const availablePermissions = ref([
      { key: 'take_exam', name: '参加考试', description: '允许参加考试' },
      { key: 'view_results', name: '查看成绩', description: '允许查看自己的考试成绩' },
      { key: 'retake_exam', name: '重考', description: '允许重新参加考试' },
      { key: 'view_analysis', name: '查看分析', description: '允许查看答题分析' }
    ])

    // 计算属性
    const isAllSelected = computed(() => {
      return students.value.length > 0 && selectedStudents.value.length === students.value.length
    })

    // 方法
    const loadStudents = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          pageSize: pageSize,
          search: searchQuery.value,
          status: statusFilter.value,
          grade: gradeFilter.value
        }
        const response = await getStudents(params)
        students.value = response.data.data
        totalPages.value = Math.ceil(response.data.total / pageSize)
      } catch (error) {
        console.error('加载学生列表失败:', error)
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
      loadStudents()
    }

    const changePage = (page) => {
      currentPage.value = page
      loadStudents()
    }

    const toggleSelectAll = () => {
      if (isAllSelected.value) {
        selectedStudents.value = []
      } else {
        selectedStudents.value = students.value.map(s => s.id)
      }
    }

    const editStudent = (student) => {
      currentStudent.value = student
      Object.assign(studentForm, {
        student_id: student.student_id,
        name: student.name,
        email: student.email,
        phone: student.phone,
        grade: student.grade,
        major: student.major
      })
      showEditModal.value = true
    }

    const saveStudent = async () => {
      try {
        if (showCreateModal.value) {
          await createStudent(studentForm)
        } else {
          await updateStudent(currentStudent.value.id, studentForm)
        }
        closeModals()
        loadStudents()
      } catch (error) {
        console.error('保存学生失败:', error)
      }
    }

    const deleteStudent = async (student) => {
      if (confirm(`确定要删除学生 ${student.name} 吗？`)) {
        try {
          await deleteStudent(student.id)
          loadStudents()
        } catch (error) {
          console.error('删除学生失败:', error)
        }
      }
    }

    const batchDelete = async () => {
      if (confirm(`确定要删除选中的 ${selectedStudents.value.length} 个学生吗？`)) {
        try {
          await batchDeleteStudents(selectedStudents.value)
          selectedStudents.value = []
          loadStudents()
        } catch (error) {
          console.error('批量删除失败:', error)
        }
      }
    }

    const resetPassword = async (student) => {
      if (confirm(`确定要重置 ${student.name} 的密码吗？`)) {
        try {
          await resetStudentPassword(student.id)
          alert('密码重置成功')
        } catch (error) {
          console.error('重置密码失败:', error)
        }
      }
    }

    const toggleStatus = async (student) => {
      const newStatus = student.status === 'active' ? 'inactive' : 'active'
      try {
        await toggleStudentStatus(student.id, newStatus)
        loadStudents()
      } catch (error) {
        console.error('切换状态失败:', error)
      }
    }

    const managePermissions = async (student) => {
      currentStudent.value = student
      try {
        const response = await getStudentPermissions(student.id)
        studentPermissions.value = response.data.permissions || []
        showPermissionModal.value = true
      } catch (error) {
        console.error('获取权限失败:', error)
      }
    }

    const savePermissions = async () => {
      try {
        await updateStudentPermissions(currentStudent.value.id, studentPermissions.value)
        closeModals()
        alert('权限更新成功')
      } catch (error) {
        console.error('保存权限失败:', error)
      }
    }

    const handleFileSelect = (event) => {
      const file = event.target.files[0]
      if (file) {
        selectedFile.value = file
      }
    }

    const importFile = async () => {
      if (!selectedFile.value) return
      
      try {
        await importStudents(selectedFile.value)
        closeModals()
        loadStudents()
        alert('导入成功')
      } catch (error) {
        console.error('导入失败:', error)
        alert('导入失败，请检查文件格式')
      }
    }

    const downloadTemplate = () => {
      // 创建模板数据
      const template = [
        ['学号', '姓名', '邮箱', '电话', '年级', '专业', '密码'],
        ['2024001', '张三', 'zhangsan@example.com', '13800138000', '2024', '计算机科学', '123456']
      ]
      
      // 这里应该使用实际的Excel导出库，如 xlsx
      console.log('下载模板', template)
      alert('模板下载功能需要集成Excel导出库')
    }

    const exportStudents = async () => {
      try {
        const params = {
          search: searchQuery.value,
          status: statusFilter.value,
          grade: gradeFilter.value
        }
        await exportStudentsAPI(params)
        alert('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
      }
    }

    const closeModals = () => {
      showCreateModal.value = false
      showEditModal.value = false
      showImportModal.value = false
      showPermissionModal.value = false
      currentStudent.value = null
      selectedFile.value = null
      Object.assign(studentForm, {
        student_id: '',
        name: '',
        email: '',
        phone: '',
        grade: '',
        major: '',
        password: ''
      })
    }

    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleDateString('zh-CN')
    }

    onMounted(() => {
      loadStudents()
    })

    return {
      students,
      loading,
      searchQuery,
      statusFilter,
      gradeFilter,
      selectedStudents,
      currentPage,
      totalPages,
      showCreateModal,
      showEditModal,
      showImportModal,
      showPermissionModal,
      currentStudent,
      selectedFile,
      studentForm,
      studentPermissions,
      availablePermissions,
      isAllSelected,
      loadStudents,
      handleSearch,
      changePage,
      toggleSelectAll,
      editStudent,
      saveStudent,
      deleteStudent,
      batchDelete,
      resetPassword,
      toggleStatus,
      managePermissions,
      savePermissions,
      handleFileSelect,
      importFile,
      downloadTemplate,
      exportStudents,
      closeModals,
      formatDate
    }
  }
}
</script>

<style scoped>
.student-management {
  padding: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header h2 {
  margin: 0;
  color: #1f2937;
}

.header .actions {
  display: flex;
  gap: 12px;
}

.filters {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  align-items: center;
  flex-wrap: wrap;
}

.search-box {
  position: relative;
  flex: 1;
  max-width: 400px;
}

.search-box i {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #6b7280;
}

.search-box input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.filters select {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.table-container {
  overflow-x: auto;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.students-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 800px;
}

.students-table th,
.students-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

.students-table th {
  background: #f9fafb;
  font-weight: 600;
  color: #374151;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status.active {
  background: #d1fae5;
  color: #065f46;
}

.status.inactive {
  background: #fee2e2;
  color: #991b1b;
}

.actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 4px;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 11px;
}

.btn-primary {
  background: #3b82f6;
  color: white;
}

.btn-outline {
  background: transparent;
  color: #6b7280;
  border: 1px solid #d1d5db;
}

.btn-success {
  background: #10b981;
  color: white;
}

.btn-warning {
  background: #f59e0b;
  color: white;
}

.btn-danger {
  background: #ef4444;
  color: white;
}

.btn:hover {
  opacity: 0.8;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 24px;
}

.batch-actions {
  position: fixed;
  bottom: 24px;
  left: 50%;
  transform: translateX(-50%);
  background: white;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  gap: 16px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h3 {
  margin: 0;
  color: #1f2937;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6b7280;
}

.modal-body {
  padding: 24px;
}

.form-row {
  display: flex;
  gap: 16px;
}

.form-group {
  flex: 1;
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 4px;
  font-weight: 500;
  color: #374151;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.import-section {
  margin-bottom: 24px;
}

.upload-area {
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s;
}

.upload-area:hover {
  border-color: #3b82f6;
  background: #f8fafc;
}

.upload-area i {
  font-size: 48px;
  color: #6b7280;
  margin-bottom: 16px;
}

.upload-area p {
  margin: 8px 0;
  color: #374151;
}

.file-info {
  font-size: 12px;
  color: #6b7280;
}

.selected-file {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #f3f4f6;
  border-radius: 6px;
  margin-top: 12px;
}

.selected-file i {
  color: #10b981;
}

.selected-file button {
  background: none;
  border: none;
  color: #6b7280;
  cursor: pointer;
  margin-left: auto;
}

.template-section {
  margin-bottom: 24px;
}

.template-section h4 {
  margin: 0 0 12px 0;
  color: #1f2937;
}

.template-table {
  width: 100%;
  border-collapse: collapse;
  margin: 12px 0;
  font-size: 12px;
}

.template-table th,
.template-table td {
  padding: 8px;
  border: 1px solid #e5e7eb;
  text-align: left;
}

.template-table th {
  background: #f9fafb;
  font-weight: 600;
}

.permissions-list {
  max-height: 400px;
  overflow-y: auto;
}

.permission-item {
  padding: 12px 0;
  border-bottom: 1px solid #e5e7eb;
}

.permission-item:last-child {
  border-bottom: none;
}

.permission-item label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  cursor: pointer;
}

.permission-desc {
  margin: 4px 0 0 24px;
  font-size: 12px;
  color: #6b7280;
}

@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
  }
  
  .filters {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    max-width: none;
  }
  
  .header .actions {
    flex-direction: column;
  }
}
</style>